﻿using UnityEngine;
using UnityEngine.UI;

using System.Collections.Generic;
namespace VFramework
{


	/// <summary>
	/// 垂直itemlist可以滚动的view，可以挂载在popwindow
	/// 主要思路的设置好item，然后append即可
	/// </summary>
	/// 
	public class VUIVerticalListView : MonoBehaviour
	{

		public ScrollRect scrollRect;
		public Scrollbar hbar;
		public Scrollbar vbar;

		public RectTransform itemContainer;
		public Image item;


		public delegate void ItemUpdateHandler (Image item, object obj);
		public ItemUpdateHandler uhander = null;        //更新item的信息的回调,调用者实现
		private List<Image> itemNodes = new List<Image> ();

		private float scrollRectWidth = 0;



		void Start ()
		{

		}


		public Image appedItem (object obj)
		{

			scrollRectWidth = scrollRect.GetComponent<RectTransform> ().rect.width;
			item.gameObject.SetActive (true);

			float h1 = item.rectTransform.sizeDelta.y;

			Image nitem = GameObject.Instantiate (item.gameObject).GetComponent<Image> ();
			nitem.transform.SetParent (itemContainer.transform, false);
			nitem.transform.localScale = Vector3.one;
			nitem.transform.localPosition = new Vector3 (scrollRectWidth * 0.5f, -itemNodes.Count * h1 - h1 * 0.5f);



			itemNodes.Add (nitem);
			updateItemByObj (nitem, obj);

			item.gameObject.SetActive (false);

			return nitem;
		}

		public void setVBarValue (float v)
		{
			vbar.value = v;
		}

		public void setHBarValue (float v)
		{
			hbar.value = v;
		}

		void setBgHeight (float height)
		{

		}

		public void clean ()
		{
			foreach (Image i in itemNodes) {
				GameObject.DestroyObject (i.gameObject);
			}

			itemNodes.Clear ();
			item.gameObject.SetActive (false);
			setBgHeight (0);
		}

		private void updateItemByObj (Image item, object obj)
		{
			if (uhander != null) {
				uhander.Invoke (item, obj);
			} else {

			}
		}

		public Image getItem (int index)
		{
			return itemNodes [index];
		}
	}

}